<template>
  <div class="layout-container w-full h-full absolute inset-0">
    <splitpanes horizontal style="height: 100%">
      <!-- 搜索-->
      <pane size="80" :class="highSearch ? 'highSearch' : 'defaultSearch'">
        <div class="layout-padding-auto layout-padding-view" style="overflow-y: auto; height: auto">
          <!-- 查询表单 -->
          <el-form :model="queryForm" ref="queryRef" @keyup.enter="handleSearchClick" label-width="130px"
                   label-position="right">
            <el-row class="el-row-cell" :gutter="24">
              <el-col :span="6" style="display: flex">
                <el-button class="buttons" type="primary" @click="goBack">{{$t('common.fanhui')}}</el-button>
                <el-form-item :label="$t('agv.taskNo')" prop="taskCode" label-width="100px" style="flex: 1">
                  <el-input v-model="queryForm.taskCode" style="width: 100%" clearable :placeholder="$t('agv.pleaseEnter')"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="$t('agv.taskStatus')" prop="tastStatus">
                  <el-select v-model="queryForm.taskStatus" clearable>
                    <el-option v-for="item in highSearch ? taskStatusOptions : options" :key="item.value"
                               :label="item.value" :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="$t('agv.date')" prop="createdate">
                  <el-date-picker
                    v-model="queryForm.createdate"
                    type="daterange"
                    unlink-panels
                    range-separator="To"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :start-placeholder="$t('wms.startTime')"
                    :end-placeholder="$t('wms.endTime')"
                    :shortcuts="shortcuts"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-show="highSearch">
                <el-form-item :label="t('agv.priority')" prop="priority" v-show="highSearch">
                  <el-select v-model="queryForm.priority" @change="select" clearable>
                    <el-option v-for="item in queryForm.priorityList" :key="item.id" :label="item.id"
                               :value="item.name"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" class="el-col-button" v-show="!highSearch">

                <el-button icon="Search" type="primary" @click="handleSearchClick">{{
                    $t('agv.inquire')
                  }}
                </el-button>
                <el-button icon="refresh" @click="resetQuery">{{ $t('agv.reset') }}</el-button>
                <el-button icon="Search" color="#ff6c00" style="color: #fff" @click="highSearch = !highSearch"
                           v-show="!highSearch">{{
                    $t('agv.advancedQuery')
                  }}
                </el-button>
                <el-button icon="Close" type="info" v-show="highSearch" @click="highSearch = false"
                           style="margin-left: -1px">{{
                    $t('agv.close')
                  }}
                </el-button>
                <el-button icon="Position" type="success" @click="equiptmentDialogRef.openAddDialog()">
                  {{ $t('agv.createTasks') }}
                </el-button>
              </el-col>
            </el-row>
            <el-row class="el-row-cell" :gutter="24" v-show="highSearch">
              <el-col :span="6">
                <el-form-item :label="$t('agv.palletType')" prop="cartonType" v-show="highSearch">
                  <el-select v-model="queryForm.cartonType" clearable>
                    <el-option v-for="item in queryForm.palletTypeList" :key="item.id" :label="item.name"
                               :value="item.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="'rcs' + t('agv.agvNo')" prop="robotTaskCode" v-show="highSearch">
                  <el-input v-model="queryForm.robotTaskCode" clearable :placeholder="t('agv.pleaseEnter')"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="t('agv.agvNo')" prop="agvCode" v-show="highSearch">
                  <el-input v-model="queryForm.agvCode" clearable :placeholder="t('agv.pleaseEnter')"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="t('agv.taskType')" prop="taskTypeName" v-show="highSearch">
                  <el-select
                    :placeholder="$t('agv.taskType')"
                    filterable
                    clearable
                    remote
                    @change="getTaskTypeClick"
                    :remote-method="getProcessList"
                    v-model="queryForm.taskTypeName"
                  >
                    <el-option v-for="item in processList" :key="item.itemValue" :label="item.itemValue" :value="item">
                      <span style="float: left">{{ item.itemText }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px"> {{
                          item.itemValue
                        }} </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="el-row-cell" :gutter="24" v-show="highSearch">
              <el-col :span="12">
                <el-form-item :label="t('agv.pick-upLocation')" v-show="highSearch">
                  <el-select
                    v-model="queryForm.fromProcessCode"
                    style="width: 170px; margin-right: 15px"
                    :remote-method="getRuleList('1')"
                    @change="getRuleClick"
                    prop="fromProcessCode"
                  >
                    <el-option v-for="item in perationList" :key="item.code" :label="item.code" :value="item.code">
                      <span style="float: left">{{ item.text }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
											{{ item.code }}
										</span>
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="queryForm.fromLineCode"
                    style="width: 170px; margin-right: 15px"
                    :remote-method="getRuleList('2')"
                    @change="getLineClick"
                    prop="fromLineCode"
                  >
                    <el-option v-for="item in lineList" :key="item.code" :label="item.code" :value="item.code">
                      <span style="float: left">{{ item.text }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
											{{ item.code }}
										</span>
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="queryForm.fromLocationCode"
                    style="width: 170px"
                    :remote-method="getRuleList('3')"
                    @change="getPositionClick"
                    prop="fromLocationCode"
                  >
                    <el-option v-for="item in locationList" :key="item.code" :label="item.code" :value="item.code">
                      <span style="float: left">{{ item.text }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
											{{ item.code }}
										</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item :label="t('agv.unloadingPosition')" v-show="highSearch">
                  <el-select
                    v-model="queryForm.toProcessCode"
                    style="width: 170px; margin-right: 15px"
                    :remote-method="getRuleList('1')"
                    @change="getRuleClick2"
                    prop="toProcessCode"
                  >
                    <el-option v-for="item in perationList" :key="item.code" :label="item.code" :value="item.code">
                      <span style="float: left">{{ item.text }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
											{{ item.code }}
										</span>
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="queryForm.toLineCode"
                    style="width: 170px; margin-right: 15px"
                    :remote-method="getRuleList('2')"
                    @change="getLineClick2"
                    prop="toLineCode"
                  >
                    <el-option v-for="item in lineList" :key="item.code" :label="item.code" :value="item.code">
                      <span style="float: left">{{ item.text }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
											{{ item.code }}
										</span>
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="queryForm.toLocationCode"
                    style="width: 170px"
                    :remote-method="getRuleList('3')"
                    @change="getPositionClick2"
                    prop="toLocationCode"
                  >
                    <el-option v-for="item in locationList" :key="item.code" :label="item.code" :value="item.code">
                      <span style="float: left">{{ item.text }}</span>
                      <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
											{{ item.code }}
										</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="el-row-cell" :gutter="24" v-show="highSearch">
              <el-col :span="6">
                <el-form-item :label="t('agv.materialCode')" prop="materialCode" v-show="highSearch">
                  <el-input v-model="queryForm.materialCode" clearable :placeholder="t('agv.pleaseEnter')"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="t('agv.palletNo')" prop="cartonCode" v-show="highSearch">
                  <el-input v-model="queryForm.cartonCode" clearable :placeholder="t('agv.pleaseEnter')"/>
                </el-form-item>
              </el-col>
              <el-col :span="6"></el-col>
              <el-col :span="6" class="el-col-button">
                <el-button icon="Search" type="primary" @click="handleSearchClick">
                  {{ $t('agv.inquire') }}
                </el-button>
                <el-button icon="refresh" @click="resetQuery">{{ $t('agv.reset') }}</el-button>
                <el-button icon="Search" color="#ff6c00" @click="highSearch = !highSearch"
                           v-show="!highSearch">{{
                    $t('agv.advancedQuery')
                  }}
                </el-button>
                <el-button icon="Close" type="info" v-show="highSearch" @click="highSearch = false"
                           style="margin-left: -1px">{{
                    $t('agv.close')
                  }}
                </el-button>
                <el-button icon="Position" type="success" @click="equiptmentDialogRef.openAddDialog()">
                  {{ $t('agv.createTasks') }}
                </el-button>
              </el-col>
            </el-row>
          </el-form>

        </div>
      </pane>
      <!--表单-->
      <pane :style="{ height: highSearch ? '75%' : '90%' }">
        <div class="layout-padding-auto layout-padding-view">
          <el-tabs type="border-card" class="tab-card" v-model="queryForm.taskStatus" @tab-click="handleClick">
            <el-tab-pane v-for="item in options" :key="item.value" :label="item.label" :name="item.value">
              <template #label>
                <span :class="item.color"><i :class="['iconfont', item.icon, 'mr-2',item.color]"></i>{{ item.label }}</span>
              </template>
              <div class="layout-padding-auto">
                <el-table
                  :data="tableList"
                  highlight-current-row
                  border
                  stripe
                  style="width: 100%; height: 100%"
                  ref="tableRef"
                  :cell-style="{ textAlign: 'center' }"
                  :header-cell-style="{ textAlign: 'center',
                   background: 'var(--el-table-row-hover-bg-color)',
                   color:'var(--el-text-color-primary)'}"
                  @row-click="handleRowClick"
                >
                  <el-table-column :label="$t('agv.taskNo')" prop="taskCode" width="160" fixed></el-table-column>
                  <el-table-column :label="$t('agv.taskType')" prop="businessTaskTypeName" width="250"
                                   fixed></el-table-column>
                  <el-table-column :label="$t('agv.taskStatus')" prop="taskStatusStr" width="110" fixed>
                    <template #default="scope">
                      <!--根据不同的状态选择不同的颜色的tag-->
                      <el-tag type="success" v-if="scope.row.taskStatusStr == '已完成'">
                        {{ scope.row.taskStatusStr }}
                      </el-tag>
                      <el-tag type="primary" v-else-if="scope.row.taskStatusStr == '未完成'">
                        {{ scope.row.taskStatusStr }}
                      </el-tag>
                      <el-tag type="danger" v-else-if="scope.row.taskStatusStr == '创建'">
                        {{ scope.row.taskStatusStr }}
                      </el-tag>
                      <el-tag type="warning" v-else-if="scope.row.taskStatusStr == '等待'">
                        {{ scope.row.taskStatusStr }}
                      </el-tag>
                      <el-tag type="success" v-else-if="scope.row.taskStatusStr == '提交'">
                        {{ scope.row.taskStatusStr }}
                      </el-tag>
                      <el-tag type="warning" v-else-if="scope.row.taskStatusStr == '等待步骤执行'">
                        {{ scope.row.taskStatusStr }}
                      </el-tag>
                      <el-tag type="success" v-else-if="scope.row.taskStatusStr == '允许放货'">
                        {{ scope.row.taskStatusStr }}
                      </el-tag>
                      <el-tag type="info" v-else>
                        {{ scope.row.taskStatusStr }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column :label="$t('agv.palletType')" prop="cartonType" width="110"></el-table-column>
                  <el-table-column :label="$t('agv.creationTime')" prop="createTime" width="160"></el-table-column>
                  <el-table-column :label="$t('agv.completionTime')" prop="taskCompleteTime"
                                   width="160"></el-table-column>
                  <el-table-column :label="$t('agv.transportedQty')" prop="qty" width="100"></el-table-column>
                  <el-table-column :label="$t('agv.priority')" prop="initPriority" width="60"></el-table-column>
                  <el-table-column :label="$t('agv.scanType')" prop="scanType" width="120"></el-table-column>
                  <el-table-column :label="$t('agv.agvNo')" prop="robotCode" width="140"></el-table-column>
                  <el-table-column :label="$t('agv.pick-upLocation')" prop="fromLocationName"
                                   width="200"></el-table-column>
                  <el-table-column :label="$t('agv.unloadingPosition')" prop="toLocationName"
                                   width="200"></el-table-column>
                  <el-table-column :label="$t('agv.unloadingPositionQty')" prop="existQty"
                                   width="120"></el-table-column>
                  <el-table-column :label="$t('agv.materialCode')" prop="materialCode" width="80"></el-table-column>
                  <el-table-column :label="$t('agv.materialName')" prop="materialName" width="80"></el-table-column>
                  <el-table-column :label="$t('agv.palletNo')" prop="cartonNo" width="160"></el-table-column>
                  <el-table-column :label="$t('agv.operation')" width="160" fixed="right">
                    <template #default="scope">
                      <el-button color="#626aef" @click.stop="logDialogRef.openLogDialog(scope.row)" icon="Setting">{{
                          $t('agv.operationLog')
                        }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination
                  class="mt-2"
                  :pageNo="queryForm.pageNo"
                  :pageSize="queryForm.pageSize"
                  :total="queryForm.total"
                  @sizeChange="handleSizeChange"
                  @currentChange="handleCurrentChange"
                ></pagination>
              </div>

            </el-tab-pane>
          </el-tabs>
        </div>
      </pane>
    </splitpanes>
    <epqForm ref="equiptmentDialogRef"></epqForm>
    <logForm ref="logDialogRef"></logForm>
  </div>
</template>

<script setup>
import { Splitpanes, Pane } from 'splitpanes'
import '@/style/tailwind.css'
import '@/assets/font/iconfont.css'
import { ref, reactive, onMounted, defineAsyncComponent, provide } from 'vue'
import { fetchList, fetchProcess, fetchTaskType } from '@/api/mes/agv'

import useI18n from '@/hooks/language'
import { AGVNumber, stateList } from '@/views/statisticsList/utils/constant'
import router from '@/router'

const { t } = useI18n()

// 任务列表
const tableList = ref()
let start = ''
let end = ''
const pagination = defineAsyncComponent(() => import('@/views/mes/agv/pagination.vue'))
const epqForm = defineAsyncComponent(() => import('./epqForm.vue'))
const logForm = defineAsyncComponent(() => import('./logForm.vue'))
const equiptmentDialogRef = ref()
const logDialogRef = ref()
// 任务状态
const taskStatusOptions = ref([
  {
    label: t('agv.all'),
    value: t('agv.all')
  },
  {
    label: t('agv.execute'),
    value: t('agv.execute')
  },
  {
    label: t('agv.accomplish'),
    value: t('agv.accomplish')
  },
  {
    label: t('agv.cancel'),
    value: t('agv.cancel')
  },
  {
    label: t('agv.submit'),
    value: t('agv.submit')
  },
  {
    label: t('agv.establish'),
    value: t('agv.establish')
  },
  {
    label: t('agv.await'),
    value: t('agv.await')
  },
])
const options = ref([
  {
    label: t('agv.all'),
    value: t('agv.all'),
    icon: 'icon-renwuguanliqi',
    color:'text-blue-600'
  },
  {
    label: t('agv.execute'),
    value: t('agv.execute'),
    icon: 'icon-dengdai',
    color:'text-yellow-600'
  },
  {
    label: t('agv.accomplish'),
    value: t('agv.accomplish'),
    icon: 'icon-chenggong1',
    color:'text-green-600'
  },
  {
    label: t('agv.cancel'),
    value: t('agv.cancel'),
    icon: 'icon-ban',
    color:'text-slate-300'
  },
])
// 高级查询
const highSearch = ref(false)
// 时间选择器
const shortcuts = [
  {
    text: t('agv.threeDaysAgo'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
      return [start, end]
    },
  },
  {
    text: t('agv.sevenDaysAgo'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: t('agv.thirtyDaysAgo'),
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
]
const getYMD = (date) => {
  // 获取年份
  const year = date.getFullYear()

  // 获取月份，注意JavaScript中的月份是从0开始的，因此需要+1
  const month = String(date.getMonth() + 1).padStart(2, '0')

  // 获取日期
  const day = String(date.getDate()).padStart(2, '0')

  // 拼接成 yyyy-MM-dd 格式的字符串
  const formattedDate = `${year}-${month}-${day}`

  return formattedDate
}
// 搜索变量
const queryRef = ref()
const processList = ref()

// 表单对象
const queryForm = reactive({
  taskCode: '', //任务编号
  agvCode: '', //AGV编号
  taskStatus: t('agv.all'), // 任务状态
  taskType: '', // 任务类型，一般是搬运
  fromProcessCode: '', //取货地工序code
  fromLineCode: '', //取货地线别code
  fromLocationCode: '', //取货地位置code
  toProcessCode: '', //放货地工序code
  toLineCode: '', //放货地线别code
  toLocationCode: '', //放货地位置code
  taskTypeName: '',
  robotTaskCode: '', // rcsAGV编号
  beginTime: start,
  endTime: end,
  createdate: [],
  materialCode: '', //物料号 多个之间用; 隔开
  cartonCode: '', //托盘号
  cartonType: '', //托盘类型 WoodCarton48  48 英寸木托盘 / WoodCarton60  60 英寸木托盘
  priority: '', //任务优先级
  pageNo: 1,
  pageSize: 20,
  total: 0, // 总条数
  pickProcess: '', //取货位置 工序
  pickLine: '', //取货位置 产线
  pickPosition: '', //取货位置 位置
  unloadingProcess: '', //取货位置 工序
  unloadingLine: '', //取货位置 产线
  unloadingPosition: '', //取货位置 位置
  pickProcessName: '',
  pickLineName: '',
  pickPositionName: '',
  unloadingProcessName: '',
  unloadingLineName: '',
  unloadingPositionName: '',
  columnRule: {
    column: [
      {
        label: t('agv.process'),
        name: 'text',
      },
      {
        label: 'code',
        name: 'code',
      },
    ],
  },
  palletTypeList: [
    //托盘号类型列表
    {
      id: 'SteelCarton48',
      name: t('agv.steelCarton48'),
    },
    {
      id: 'SteelCarton60',
      name: t('agv.steelCarton60'),
    },
    {
      id: 'WoodCarton48',
      name: t('agv.woodCarton48'),
    },
    {
      id: 'WoodCarton60',
      name: t('agv.woodCarton60'),
    },
  ],
  palletType: '', //托盘类型
  priorityList: [
    {
      id: 1,
      name: 1,
    },
    {
      id: 2,
      name: 2,
    },
    {
      id: 3,
      name: 3,
    },
    {
      id: 4,
      name: 4,
    },
    {
      id: 5,
      name: 5,
    },
  ],
})

// 获取任务类型列表
const getProcessList = () => {
  fetchTaskType({}).then((res) => {
    processList.value = res.result
  })
}
// 任务类型选择
const getTaskTypeClick = (x) => {
  queryForm.taskType = x.itemValue
  queryForm.taskTypeName = x.itemText
}
const perationList = ref([]) //工序列表
const lineList = ref([]) //产线列表
const locationList = ref([]) //位置列表
// 获取工序 产线 位置列表
const getRuleList = (type) => {
  if (type === '1') {
    fetchProcess({
      type: type,
      parentCode: '',
      scanType: '',
    }).then((res) => {
      perationList.value = res.result
    })
  } else if (type === '2') {
    fetchProcess({
      type: type,
      parentCode: '',
      scanType: '',
    }).then((res) => {
      lineList.value = res.result
    })
  } else if (type === '3') {
    fetchProcess({
      type: type,
      parentCode: '',
      scanType: '',
    }).then((res) => {
      locationList.value = res.result
    })
  }
}

// 取货位置选择 工序 产线 位置
const getRuleClick = (e) => {
  queryForm.pickProcess = e.code
  queryForm.pickProcessName = e.text
}
const getLineClick = (e) => {
  queryForm.pickLine = e.code
  queryForm.pickLineName = e.text
}
const getPositionClick = (e) => {
  queryForm.pickPosition = e.code
  queryForm.pickPositionName = e.text
}
// 放货位置选择 工序 产线 位置
const getRuleClick2 = (e) => {
  queryForm.unloadingProcess = e.code
  queryForm.unloadingProcessName = e.text
}
const getLineClick2 = (e) => {
  queryForm.unloadingLine = e.code
  queryForm.unloadingLineName = e.text
}
const getPositionClick2 = (e) => {
  queryForm.unloadingPosition = e.code
  queryForm.unloadingPositionName = e.text
}
// 校验 状态的选择事件
const select = (e) => {
  queryForm.selectId = e?.id
}

// 点击tab切换
const handleClick = (tab) => {
  queryForm.taskStatus = tab.props.name
  getdataList()
}
// 获取数据列表
const getdataList = () => {
  if (queryForm.createdate.length > 0) {
    queryForm.beginTime = getYMD(new Date(queryForm.createdate[0]))
    queryForm.endTime = getYMD(new Date(queryForm.createdate[1]))
  }
  fetchList({ ...queryForm }).then((res) => {
    tableList.value = res.result.items
    queryForm.pageNo = res.result.page
    queryForm.pageSize = res.result.pageSize
    queryForm.total = res.result.total
  })
}
const handleRowClick = (e) => {
  equiptmentDialogRef.value.openAddDialog(e)
}
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  getdataList()
}
const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  getdataList()
}
// 点击查询
const handleSearchClick = async () => {
  getdataList()
}
// 点击重置
const resetQuery = () => {
  queryForm.fromProcessCode = ''
  queryForm.fromLineCode = ''
  queryForm.fromLocationCode = ''
  queryForm.toProcessCode = ''
  queryForm.toLineCode = ''
  queryForm.toLocationCode = ''
  queryForm.beginTime = ''
  queryForm.endTime = ''
  queryForm.taskType = ''
  queryForm.taskStatus = t('agv.all')
  queryRef.value?.resetFields()
  getdataList()
}
const goBack =() =>{
  router.back()
}
// 初始化数据
onMounted(async () => {
  getdataList()
})
provide('getdataList', getdataList)
</script>

<style lang="scss" scoped>
.defaultSearch {
  height: 65px !important;
}

.highSearch {
  height: 222px !important;
}

.layout-container {
  padding: 10px;
}

.el-row-cell :deep(.el-col) {
  height: 50px;
}

.el-row-cell :deep(.el-input ) {
  width: 100% !important;
}

.el-row-cell :deep(.el-select) {
  width: 100% !important;
}

.el-row-cell :deep(.el-cascader) {
  width: 100% !important;
}

.el-row-cell :deep(.el-date-editor) {
  width: 100% !important;
}

.el-col-button {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}

:deep(.el-pagination) {
  margin-top: 5px;
  justify-content: flex-end;
}

</style>
